package com.etl.dataflow.executor.util;

import cn.hutool.core.bean.BeanUtil;
import com.etl.dataflow.common.entity.JdbcProperties;
import com.etl.dataflow.executor.connectivity.ConnectorFactory;
import com.etl.dataflow.executor.connectivity.TypedJdbcProperties;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author dx
 */
public class JdbcQuerySaveUtil {

    private JdbcQuerySaveUtil() {
    }

    public static Connection getConnection(JdbcProperties jdbcProperties) throws SQLException {
        TypedJdbcProperties typedJdbcProperties = new TypedJdbcProperties();
        BeanUtil.copyProperties(jdbcProperties, typedJdbcProperties);
        return ConnectorFactory.getConnector(typedJdbcProperties).getConnection(jdbcProperties);
    }

    public static void closeResultSet(ResultSet rs) {
        try {
            if (null != rs) {
                Statement stmt = rs.getStatement();
                if (null != stmt) {
                    stmt.close();
                }
                rs.close();
            }
        } catch (SQLException e) {
            throw new IllegalStateException(e);
        }
    }

    public static synchronized void closeDbResources(ResultSet rs, Statement stmt,
                                                     Connection conn) {
        if (null != rs) {
            try {
                rs.close();
            } catch (SQLException ignored) {
            }
        }

        if (null != stmt) {
            try {
                stmt.close();
            } catch (SQLException ignored) {
            }
        }

        if (null != conn) {
            try {
                conn.close();
            } catch (SQLException ignored) {
            }
        }
    }

    public static void closeDbResources(Statement stmt, Connection conn) {
        closeDbResources(null, stmt, conn);
    }

    public static ResultSet query(Connection conn, String sql)
            throws SQLException {
        Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        //默认3600 seconds
        stmt.setQueryTimeout(3600);
        stmt.setFetchSize(1000);
        return query(stmt, sql);
    }

    public static ResultSet query(Statement stmt, String sql)
            throws SQLException {
        return stmt.executeQuery(sql);
    }

    public static long count(Connection conn, String sql)
            throws SQLException {
        ResultSet rs = query(conn, sql);
        long count = -1;
        if (rs.next()) {
            count = rs.getBigDecimal(1).longValue();
        }
        closeResultSet(rs);
        return count;
    }

}
